package com.itsu.integration.component;

import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author suben
 * @date 2020/5/8 14:09
 */
public class CustomMappingJackson2StringMessageConverter extends MappingJackson2HttpMessageConverter {

    @Override
    protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
//        beanutils.copy
        try {
            String str = JSON.toJSONString(object);
            str = jsonParamNameFirstOneConvert(str, 1);
            System.err.println(str);
            Map map = JSON.parseObject(str);
            System.out.println(map);
            super.writeInternal(map, type, outputMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String jsonParamNameFirstOneConvert(String str, Integer rule) {
        String splitRule0 = "", splitRule1 = ":", splitRule2 = ",\"", splitRule3 = "\"", splitRule4 = "{", splitRule5 = "[";
        String[] split = str.split(splitRule1);
        List<String> params = new LinkedList<>();
        for (int i = 0; i < split.length; i++) {
            if (i == (split.length - 1)) {
                break;
            }
            String[] ss = split[i].split(splitRule2);
            String result = ss[ss.length - 1].replace(splitRule3, splitRule0).replace(splitRule4, splitRule0).replace(splitRule5, splitRule0);
            params.add(result);
        }
        for (String param : params) {
            String newParam = null;
            if (rule.equals(1)) {
                newParam = toUpperCaseFirstOne(param);
            } else {
                newParam = toLowerCaseFirstOne(param);
            }
            str = str.replace(param, newParam);
        }
        return str;

    }

    /**
     * 首字母转小写
     *
     * @param str
     * @return
     */
    public static String toLowerCaseFirstOne(String str) {
        if (Character.isLowerCase(str.charAt(0)))
            return str;
        else
            return (new StringBuilder()).append(Character.toLowerCase(str.charAt(0))).append(str.substring(1)).toString();
    }


    /**
     * 首字母转大写
     *
     * @param str
     * @return
     */
    public static String toUpperCaseFirstOne(String str) {
        if (Character.isUpperCase(str.charAt(0)))
            return str;
        else
            return (new StringBuilder()).append(Character.toUpperCase(str.charAt(0))).append(str.substring(1)).toString();
    }
}
